package com.ramos.kuaixiao.network;

import android.os.AsyncTask;
import android.util.Log;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.SyncHttpClient;
import com.ramos.kuaixiao.App;
import com.ramos.kuaixiao.db.BrandKeywordsDB;
import com.ramos.kuaixiao.db.PriceDB;
import com.ramos.kuaixiao.entity.BrandKeywords;
import com.ramos.kuaixiao.entity.FirstPrice;
import com.ramos.kuaixiao.utils.CommUtil;
import com.ramos.kuaixiao.utils.FileUtil;
import com.ramos.kuaixiao.utils.NetUtils;
import com.ramos.kuaixiao.utils.SharedPreference;
import com.ramos.kuaixiao.utils.Utils;

import org.apache.http.Header;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class DownloadKeyWordsTask extends AsyncTask<Void, Integer, Boolean> {
    private final static String TAG = "DownloadKeyWordsTask";

    @Override
    protected void onPreExecute() {

    }

    @Override
    protected Boolean doInBackground(Void... params) {
        try {
            //获取所有品牌分类
            getAllKeywords();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    private void getAllKeywords() {
        File file  = new File(FileUtil.getDataPath(App.mContext) + "/tbl_brandkeywords.csv");
        List<BrandKeywords> list = readBrandKeywordsCsv(file.getAbsolutePath());
        CommUtil.d(App.mContext,TAG, "tbl_BrandKeywords:" + list.size());
        BrandKeywordsDB db = new BrandKeywordsDB();
        db.addAll(list);
    }

    public List<BrandKeywords> readBrandKeywordsCsv(String path) {
        List<BrandKeywords> readerArr = new ArrayList<>();
        Scanner in = Utils.readCsv(path);
        try {
            in.nextLine();
            while (in.hasNextLine()) {
                String[] lines = in.nextLine().split(",");
                //Log.d(TAG, "ProductPrice:" + lines[3] + " " + lines[4] + " " + lines[2] + " " + lines[1] + " " + lines[8] + " " + lines[5] + " " + lines[6] + " " + lines[7]);
                BrandKeywords bean = new BrandKeywords(Utils.replaceStr(lines[0]),Utils.replaceStr(lines[1]), Utils.replaceStr(lines[2]), Utils.replaceStr(lines[3]), Utils.replaceStr(lines[4]),Long.valueOf(Utils.replaceStr(lines[5])));
                readerArr.add(bean);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return readerArr;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {

    }

    @Override
    protected void onPostExecute(Boolean result) {

    }

    private void getAllPrice() {
        try {
            String url = NetUtils.PRODUCT_PRICE;
            String path = url + SharedPreference.getPreferString("dealer");
            Log.d(TAG, "PRODUCT_PRICE：path=" + path);
            SyncHttpClient client = new SyncHttpClient(); // 创建异步请求的客户端对象
            // 创建请求参数的封装的对象
            client.setTimeout(120000);
            client.get(path, new AsyncHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    //statusCode:状态码    headers：头信息  responseBody：返回的内容，返回的实体
                    //判断状态码
                    try {
                        String result = new String(responseBody, "utf-8");
                        JSONObject jsonObejct = JSONObject.parseObject(result);
                        Log.d(TAG, "PRODUCT_PRICE:result=" + result);
                        if (jsonObejct.getInteger("status") == 200) {
                            JSONObject data = jsonObejct.getJSONObject("data");
                            StringBuilder stringBuilder = new StringBuilder();
                            stringBuilder.append(data.getJSONArray("rows").toString());
                            List<FirstPrice> customerList = JSONArray.parseArray(stringBuilder.toString(), FirstPrice.class);
                            if (customerList != null && customerList.size() > 0) {
                                Log.d(TAG, "PRODUCT_PRICE:mCustomerList=" + customerList.size());
                                PriceDB customerDB = new PriceDB();
                                customerDB.addAllPrice(customerList);

                            }
                            stringBuilder = null;
                            customerList= null;
                        }
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers,
                                      byte[] responseBody, Throwable error) {
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
